package org.lzy.shop.activity

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.chad.library.adapter4.layoutmanager.QuickGridLayoutManager
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.lzy.shop.Constant
import org.lzy.shop.adapter.SearchGoodAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivitySearchresultBinding
import org.lzy.shop.good.GoodInfoActivity
import org.lzy.shop.viewmodel.SearchModel

/**
 * 搜索结果
 */
class SearchResultActivity : BaseMvvmActivity<ActivitySearchresultBinding, SearchModel>({ ActivitySearchresultBinding.inflate(it) }),
    OnRefreshListener {


    // 排序类型常量
    companion object {
        private const val TYPE_DEFAULT = 1
        private const val TYPE_SALES = 2
        private const val TYPE_PRICE = 3
        private const val FIRST_PAGE = 1
    }

    private var searchType: Int = TYPE_DEFAULT
    private var featured: Boolean = true
    private var mPageIndex = FIRST_PAGE
    private var mSearchName: String? = null
    private var mTypeId: ArrayList<Int>? = null
    private var typeIdArray: JSONArray? = null
    private var mOrderField: String = ""
    private var mOrderDirection: String = "desc"

    // 加载状态管理
    private var isLoading = false
    private var hasMoreData = true


    // 使用空安全的延迟初始化
    private val searchGoodAdapter: SearchGoodAdapter by lazy { SearchGoodAdapter() }


    override fun initView() {
        if (intent.extras != null) {
            val bundle = intent.extras
            mSearchName = bundle!!.getString(Constant.GOODSTITLE)
            mTypeId= bundle.getIntegerArrayList(Constant.TYPE_ID)
            featured = bundle.getBoolean(Constant.FEATURE)
            binding.searchEdit.setText(mSearchName)
        }

        binding.recyclerview.apply {
            layoutManager= QuickGridLayoutManager(this@SearchResultActivity, 2)
            adapter = searchGoodAdapter
            setItemViewCacheSize(10)  // 减少缓存大小，根据实际情况调整
            setHasFixedSize(true)
        }
        binding.refreshLayout.apply {
            // 设置刷新监听器
            setOnRefreshListener(this@SearchResultActivity)
        }

        // 添加滚动监听器来实现加载更多功能
        binding.recyclerview.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 只有向上滚动且有更多数据且未在加载中时才检查是否需要加载更多
                if (dy <= 0 || isLoading || !hasMoreData) return

                val layoutManager = recyclerView.layoutManager as? androidx.recyclerview.widget.GridLayoutManager
                if (layoutManager != null &&
                    !binding.refreshLayout.isRefreshing &&
                    layoutManager.findLastVisibleItemPosition() >= searchGoodAdapter.itemCount - 2) { // 提前2个item开始加载
                    loadMoreData()
                }
            }
        })

        // 定义加载更多数据的方法
        fun loadMoreData() {
            isLoading = true
            // 在UI上可以显示加载更多的提示
            mPageIndex++
            getSearchResult()
            // 加载完成后会在initData的observer中设置isLoading为false
        }
        searchGoodAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position)
            item?.let {
                val bundle = Bundle()
                bundle.putInt(Constant.GOODID, item.id)
                bundle.putString(Constant.GOODPIC, item.mainPic)
                startActivity(GoodInfoActivity::class.java, bundle)
            }
        }
    }

    //搜索结果
    fun getSearchResult(){
        lifecycleScope.launch {
            try {
                mViewModel.getSearchResult(mPageIndex, binding.searchEdit.text.toString(), mTypeId, mOrderField, mOrderDirection)
            } catch (e: Exception) {
                e.printStackTrace()
                finishRefresh()

            }
        }

    }

    override fun initData() {
        mViewModel.searchGoodsData.observeWithLifecycle(this) { searchGoodsResponse ->
            finishRefresh()

            // 设置加载状态为false
            isLoading = false

            searchGoodsResponse?.let {
                if (searchGoodsResponse.isNotEmpty()) {
                    if (mPageIndex == FIRST_PAGE) {
                        searchGoodAdapter.submitList(searchGoodsResponse)
                    } else {
                        searchGoodAdapter.addAll(searchGoodsResponse)
                    }

                    // 设置有更多数据
                    hasMoreData = true
                } else {
                    if (mPageIndex > FIRST_PAGE) {
                        // 没有更多数据了
                        hasMoreData = false
                        // 可以在这里显示"没有更多数据"的提示
                    } else {
                        showListEmpty()
                    }
                }
            }
        }
    }

    // 定义加载更多数据的方法
    private fun loadMoreData() {
        isLoading = true
        // 在UI上可以显示加载更多的提示
        mPageIndex++
        getSearchResult()
        // 加载完成后会在initData的observer中设置isLoading为false
    }



    override fun requestData() {
        // 转换类型ID格式
        try {
            typeIdArray = JSONArray(mTypeId)
        } catch (e: Exception) {
        }
        getSearchResult()
    }

    override fun allClick() {
        // 综合
        binding.layoutGoodsCalssifyHeadLlDefault.setOnClickListener {
            searchType = TYPE_DEFAULT
            mOrderField = ""
            mPageIndex = FIRST_PAGE
            getSearchResult()
        }

        // 销量排序
        binding.layoutGoodsCalssifyHeadLlSales.setOnClickListener {
            handleSortClick(TYPE_SALES, "sold", binding.layoutGoodsCalssifyHeadIvSale)
        }

        // 价格排序
        binding.layoutGoodsCalssifyHeadLlPrice.setOnClickListener {
            handleSortClick(TYPE_PRICE, "price", binding.layoutGoodsCalssifyHeadIvPrice)
        }

        // 搜索
        binding.searchBtn.setOnClickListener {
            mPageIndex = FIRST_PAGE
            getSearchResult()
        }
    }

    // 处理排序点击的通用方法
    private fun handleSortClick(type: Int, orderField: String, rotationView: android.view.View) {
        searchType = type
        mOrderField = orderField

        // 切换排序方向
        mOrderDirection = if (mOrderDirection == "asc") "desc" else "asc"

        // 更新图标旋转
        rotationView.rotation = if (mOrderDirection == "desc") 90f else 270f

        // 重置页码并搜索
        mPageIndex = FIRST_PAGE
        getSearchResult()
    }

    private fun finishRefresh() {
        // 停止刷新动画
        binding.refreshLayout.isRefreshing = false
    }

    private fun showListEmpty() {
        searchGoodAdapter.submitList(null)
        searchGoodAdapter.isStateViewEnable = true
        searchGoodAdapter.stateView = showEmptyView()
    }

    override fun onRefresh() {
        // 重置页码并重新获取数据
        mPageIndex = FIRST_PAGE
        getSearchResult()
    }
}